/**
  * @description: url工具类
  * @author: lxz
  * @update: lxz(2021-01-18)
  */

/**
 * 拆解url
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * 对象转url参数字符串
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return ''
  return Object.keys(json).reduce((arr, key) => {
    if (!json[key]) return arr
    arr.push(encodeURIComponent(key) + '=' + encodeURIComponent(json[key]))
    return arr
  }, []).join('&')
}

/**
 * 获取url中的参数值
 * @param {String}     keyName  字段key名称
 * @param {String=}    url      查找的url(默认值当前地址栏的参数)
 * @returns {String}            字段key对应的值
 */
export function getQueryString(name, url = location.href) {
  const reg = new RegExp('(^|&|\\?)' + name + '=([^(&|#|\\?)]*)(&|\\?|#|$)', 'i')
  const l = decodeURI(url)
  const r = l.substr(1).match(reg)
  if (r != null) {
    return unescape(r[2])
  }
  return null
}
